package org.jadelyre.core.worker;

import org.jadelyre.core.task.EntryQueue;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class Worker<T> {

    protected ThreadPoolExecutor executor;
    protected EntryQueue<T> entryQueue;
    protected int threshold = 10;//是否需要添加新task的阀值
    protected AtomicInteger taskCount = new AtomicInteger();
    private volatile boolean terminated = false;
    private boolean optimize;

    public Worker(ThreadPoolExecutor executor, EntryQueue<T> entryQueue, boolean optimize) {
        this.executor = executor;
        this.entryQueue = entryQueue;
        this.optimize = optimize;
    }

    public void work(T t) {
        if (terminated) {
            return;
        }
        if (optimize) {
            entryQueue.addEntry(t);
            if (taskCount.get() == 0) {
                //没有执行的task,添加
                taskCount.getAndIncrement();
                execute();
                return;
            }
            int count = entryQueue.getCount();
            if (count >= threshold) {
                //超过阀值，添加新的task
                taskCount.getAndIncrement();
                execute();
                return;
            }
        } else {
            entryQueue.addEntry(t);
            execute();
        }


    }

    protected abstract void execute();

    public AtomicInteger getTaskCount() {
        return taskCount;
    }

    public EntryQueue<T> getEntryQueue() {
        return entryQueue;
    }

    public boolean isTerminated() {
        return terminated;
    }

    public void setTerminated(boolean terminated) {
        this.terminated = terminated;
    }

    public void setOptimize(boolean optimize) {
        this.optimize = optimize;
    }
}
